<!DOCTYPE html>
<html>
<head>
  <title>Spy / Stub / Clock</title>
  <link rel="stylesheet" href="styles.css" />
</head>
<body>
  <h1>Favorite Fruits</h1>
  <ul class="favorite-fruits"></ul>

  <script>
    function updateFavoriteFruits (contents) {
      if (typeof contents !== 'string') {
        contents = contents.map((item) => `<li>${item}</li>`).join('')
      }

      document.querySelector('.favorite-fruits').innerHTML = contents
    }

    function getFavoriteFruits () {
      document.querySelector('.favorite-fruits').innerHTML = '<div class="loader"></div>'

      fetch('/favorite-fruits')
      .then((response) => {
        if (response.ok) {
          return response.json()
        } else {
          throw new Error(response.statusText)
        }
      })
      .then((response) => {
        updateFavoriteFruits(response.length ? response : 'No favorites')
      })
      .catch((error) => {
        updateFavoriteFruits(`Failed loading favorite fruits: ${error.message}`)
      })
    }

    getFavoriteFruits()
    setInterval(getFavoriteFruits, 30000)
  </script>
</body>
</html>
